package com.mall.order.services;

import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /***
     *
     * @param orderID:订单ID
     * @param success:订单的是否支付成功
     *         如果支付成功:
     *           访问tb_stock扣减锁定库存
     *            	 a.  根据订单id，查询到所有订单商品条目
     *               b.  遍历每一个订单 商品条目，根据购买的数量，扣减对应商品的锁定库存\
     *        如果失败
     *            修改tb_payment中的对应订单的支付状态，支付成功时间，完成时间  PAY_FAIL("3","支付失败");
     */
    @Override
    public void changeOrderStatus(String orderID, boolean success) {
        if (success) {
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderID);
            List<Long> productIdList = orderItemMapper.selectByExample(example).stream().map(OrderItem::getItemId).collect(Collectors.toList());
            // 更新orderId对应的Item的库存状态
            orderItemMapper.updateStockStatus(3, orderID);
            // 更新订单表状态
            orderMapper.updateOrderSuccess(orderID);
            // 更新库存
            if (productIdList.size() != 0) {
                stockMapper.reduceStock(productIdList);
            }
        }
    }

}
